import foldWrap from "../commonComponents/fold.vue"
import actionSheet from "../commonComponents/actionSheet.vue"
import textarea_y from "../commonComponents/adviseTextarea.vue"
import voiceTxtArea from "../commonComponents/voiceTxtarea.vue"
import detailTemplate from "../commonComponents/detailTemplate.vue"
import templateItems from "../commonComponents/templateItems.vue"
import leaderAdviseList from "../progressPublic/leaderAdviseList.vue"
import zjJudgeList from "../progressPublic/zjJudgeList.vue"
import phoneCall from "../progressPublic/phoneCall.vue"

export default {
  data() {
    return {
      bodyShow: false,
      switch_cs_show: false,
      actionShow: false,
      isCenter: false,
      zjJudgeBackList: [],
      assetList: [],
      emList: [],
      showControl: {},
      base: {
        beforePublish: false,
        afterPublish: false,
        warnSubmitList: false,
        eventSubmitList: false,
      },
      fileList: [],
      myTaskSubmitList: [1],
      details: {
        baseInfo: {},
      },
      detailMyTask: {},
      actionData: [
        {txt: '加入工具包', iconClass: "", value: 1},
        {txt: '下载文件', iconClass: "", value: 2}
      ],
    }
  },
  methods: {
    init() {

      let title = {
        label: "标题",
        id: "title",
        value: "",
        singleLine: 0,
        type: 1,
      };

      let happenTime = {
        label: "发生日期",
        id: "happenTime",
        value: "",
        singleLine: 1,
        type: 1,
      };

      let sendDeptname = {
        label: "报送单位",
        id: "sendDeptname",
        value: "",
        singleLine: 1,
        type: 1,
      };

      let sendUsername = {
        label: "填报人",
        id: "sendUsername",
        value: "",
        singleLine: 1,
        type: 1,
      };

      let phone = {
        label: "联系电话",
        id: "phone",
        value: "",
        singleLine: 1,
        type: 1,
      };

      let attachment = {
        label: "附件",
        id: "fileIds",
        singleLine: 0,
        value: [],
        type: 2,
      };

      this.base.warnSubmitList = {
        title,
        eventType: {
          label: "风险类型",
          value: "",
          singleLine: 1,
          type: 1,
        },
        level: {
          label: "风险等级",
          value: "",
          singleLine: 1,
          type: 1,
        },
        happenTime,
        sendDeptname,
        sendUsername,
        phone,
        fax: {
          label: "传真",
          value: "",
          singleLine: 1,
          type: 1,
        },
        regionListString: {
          label: "影响范围",
          singLine: 1,
          type: 1,
          value: "",
        },
        industryListString: {
          label: "影响行业",
          value: "",
          singleLine: 0,
          type: 1,
        },
        influenceHarm: {
          label: "影响和危害描述",
          value: "",
          singleLine: 0,
          type: 1,
        },
        basicSituationDescription: {
          label: "基本情况描述",
          singLine: 0,
          type: 1,
          value: "",
        },
        verificationMethod: {
          label: "验证方法",
          singLine: 0,
          type: 1,
          value: "",
        },
        trendHazards: {
          label: "发展趋势及可能危害",
          singLine: 0,
          type: 1,
          value: "",
        },
        measureToken: {
          label: "已采取的措施及效果",
          singLine: 0,
          type: 1,
          value: "",
        },
        suggestion: {
          label: "建议应对措施",
          singLine: 0,
          type: 1,
          value: "",
        },
        remarks: {
          label: "备注",
          singLine: 0,
          type: 1,
          value: "",
        },
        attachment,
      };

      this.base.eventSubmitList = {
        title,
        eventType: {
          label: "事件类型",
          value: "",
          singleLine: 1,
          type: 1,
        },
        level: {
          label: "事件等级",
          value: "",
          singleLine: 1,
          type: 1,
        },
        happenTime,
        sendDeptname,
        sendUsername,
        phone,
        fax: {
          label: "传真",
          value: "",
          singleLine: 1,
          type: 1,
        },
        regionListString: {
          label: "影响地域",
          value: "",
          singleLine: 0,
          type: 1,
        },
        industryListString: {
          label: "影响行业",
          value: "",
          singleLine: 0,
          type: 1,
        },
        influenceHarm: {
          label: "影响和危害描述",
          value: "",
          singleLine: 0,
          type: 1,
        },
        unitSystemDescription: {
          label: "事件描述",
          value: "",
          singleLine: 0,
          type: 1,
        },
        primaryJudgment: {
          label: "事态发展概述及初判原因",
          value: "",
          singleLine: 0,
          type: 1,
        },
        measureToken: {
          label: "已采取的措施及效果",
          value: "",
          singleLine: 0,
          type: 1,
        },
        itemsAdvise: {
          label: "请求事项及工作建议",
          value: "",
          singleLine: 0,
          type: 1,
        },
        remarks: {
          label: "备注",
          value: "",
          singleLine: 0,
          type: 1,
        },
        attachment,
      };

      this.bodyShow = false;

      this.$store.commit("_leaderAdvise", []);

      this.headerType = this.$store.state.showFlag;

      this.urlType = parseInt(_methods.getUrlParam("type")) * 10;

      _methods.headerTitleChange(this.urlType);

      _data.processSubmitData.userIds = "";

      //flag 1 事件管理进入详情  2 我的任务进入详情

      // listType:列表类型（1 首页，2 我的任务 3首页）

      // type：2 事件 3预警 10 风险提示

      this.flag = parseInt(_methods.getUrlParam("listType"));

      this.infoType = parseInt(_methods.getUrlParam("type"));

      this.id = _methods.getUrlParam("id");

      this.dPath = {
        1: "/riskDetail/",
        2: "/myTaskList/",
        4: "/workReport/",
      }[this.flag];

      this.eventDetailGet();
    },
    //事件详情获取
    eventDetailGet() {
      // this.flag :列表类型（1 首页，2 我的任务 3首页）
      let self = this;
      let url;
      let type;
      let ajUrl;
      let data = {};
      if (this.flag == 2) {
        url = _ajaxUrls.selfTasksDetail.url;
        type = _ajaxUrls.selfTasksDetail.type;
        data.id = this.id;
      }
      else {
        ajUrl = {
          20: _ajaxUrls.eventList,
          30: _ajaxUrls.riskManage,
          100: _ajaxUrls.riskManage,
        }[this.urlType];
        url = ajUrl.url + `/${this.id}`;
        type = ajUrl.type;
      }
      _ajax.noLoading(url,
        data,
        (ajData) => {
          let data = ajData.result;
          let infoDetailData;
          data.urlType = self.urlType;
          let infoList = {
            20: this.base.eventSubmitList,
            30: this.base.warnSubmitList,
            100: this.base.warnSubmitList,
          }[self.urlType];

          if (this.flag == 2) {
            //type 2事件 3预警
            let key = {
              20: "reEvent",
              30: "reRisk",
            }[this.urlType];
            infoDetailData = data[key];

            let lb = {
              3: "应对要求",
              4: "反馈要求",
              5: "协调处置要求",
            }[_data.userInfo.roleRank];

            data.replyClaimDw = data[key].replyClaim;

            data.handleClaim = data[key].handleClaim;


            let ct = {
              3: "replyClaimDw",
              4: "replyClaim",
              5: "handleClaim",
            }[_data.userInfo.roleRank];

            if (data.downsSet) {
              _methods.feedBackList(data.articleID, data.downsSet, data).then(v => {
                this.$store.commit("_downsSet", v);
              });
            }

            data.ew = {
              label: lb,
              content: data[ct],
              downsSet: data.downsSet
            };
          }
          else {
            infoDetailData = data;
          }
          let bs = parseInt(data.status);
          {
            // 基本信息
            for (let key in infoDetailData) {
              let val = infoDetailData[key];
              if (val && this.base.beforePublish[key]) {
                this.base.beforePublish[key].value = val;
              }
              if (val && infoList[key]) {
                infoList[key].value = val;
              }
            }

            infoList.sendDeptname.value = infoDetailData.createUserInfo.orgName;
            infoList.sendUsername.value = infoDetailData.createUserInfo.linkdoodName;
            infoList.phone.value = infoDetailData.createUserInfo.cellphone;

            if (self.urlType === 20) {
              if (infoDetailData.firstEventType && infoDetailData.secondEventType) {
                infoList.eventType.value = infoDetailData.firstEventType.name + " — " + infoDetailData.secondEventType.name;
              }
              infoList.level.value = window._data.eventLevel[infoDetailData.primaryEventGrade];
            } else {
              infoList.eventType.value = infoDetailData.riskType.name;
              infoList.level.value = window._data.riskLevel2[infoDetailData.primaryRiskGrade];
            }
            //附件
            infoList.attachment.value = infoDetailData.attachmentList || [];
          }
          _data.userInfo.isCenterInit(() => {
              this.$store.commit("_leaderAdvise", infoDetailData.approvalList);
              this.assetListGet(data.assetList);
              this.isCenter = true;
            },
            () => {
              let al = {
                3: "应对情况",
                4: "反馈情况",
                5: "响应反馈",
              }[_data.userInfo.roleRank];
              let ia = {
                isSubmit: 99,
                attributesValue: "",
                isRequired: 1,
                size: 1000,
                element: "textarea",
                id: "response",
                placeholder: "",
                label: al,
              };
              if (bs != 0) {
                //已办
                ia.attributesValue = data.response;
                data.attributeList.unshift(ia);
                data.attributeList = _methods.temRead(data.attributeList);
              }
              else {
                //待办
                data.attributeList.unshift(ia);
                data.attributeList = _methods.temFormat(data.attributeList);
              }
            });

          data.baseInfo = infoList;
          data.control = window._methods.processSubmitControl(data);
          self.details = data;
          this.bodyShow = true;
        },
        type);
    },
    //资产格式化
    assetListGet(data) {
      let list = [];
      for (let key in data) {
        let obj = {
          name: "",
          list: [],
        };
        obj.list = data[key];
        obj.name = key;
        list.push(obj);
      }
      this.assetList = list;
    },
    checkAsset(item) {
      _data.checkAsset = item.map(i => {
        i.title = '　';
        i.list = _methods.temRead(i.extend);
        return i;
      });
      _methods.goPath(`${this.dPath}assetDetail`);
    },
    //事件提交
    eventSubmit(type = 2) {

      let self = this;

      let ajUrl = {
        20: window._ajaxUrls.eventApproval.url,
        30: _ajaxUrls.riskApproval.url,
        100: _ajaxUrls.riskApproval.url,
      }[this.urlType];

      let advice = window._methods.getValue("ldv");

      let sd = {
        advice, //研判意见
        articleID: this.id, //请示人ID
        type: type //1.转批2.同意3.退回4.归档
      };
      if (type === 1) {
        sd.approvalUserID = window._data.processSubmitData.userIds;
      }

      _ajax.confirmWithLoading(ajUrl, sd,
        () => {
          _alert.alert(() => {
            self.detailRefresh();
          });
        },
        "put");
    },
    goLeaders() {
      window._methods.goPath("/riskDetail/people?code=1");
    },
    detailRefresh(flag) {
      _vrvInit.isPushCloseWindow();
      if (flag === 1) {
        _methods.goBack();
      } else {
        this.init();
      }
      // this.flag:列表类型（1 首页，2 我的任务 3首页）
      if (this.flag === 1) {
        window._methods.indexLIstRefresh();
      } else {
        window._methods.myTaskLIstRefresh();
      }
    },
    detailRefreshMyTask(flag) {
      if (flag === 1) {
        _methods.goBack();
      } else {
        this.init();
      }
      _methods.myTaskLIstRefresh();
    },
    //发布流程
    eventAndWarnPublish() {
      let self = this;
      let sd = {
        replyClaim: _methods.getValue("replyClaim"),//应对要求
        downsSet: JSON.stringify(self.$store.state.orgChecked.val.map(i => {
          return i.orgID;
        })),//选择的下发单位
        handleClaim: _methods.getValue("handleClaim"),//应对要求
        manufacturers: JSON.stringify(self.$store.state.dwChecked.val.map(i => {
          return i.orgID;
        })),
        attributesIDs: self.$store.state.feedBackItemCheck.map(i => {
          return i.id;
        }).join(","),
        safeAttributeIDS: self.$store.state.feedBackItemCheck.map(i => {
          return i.id;
        }).join(","),
      };
      let ajUrl;
      let flag = true;
      let feedbackType = {
        20: 3,
        30: 2,
        100: 2,
      }[this.urlType];
      sd.feedbackType = feedbackType;

      if (_data.userInfo.roleRank == 3) {
        sd.id = this.id;
        ajUrl = _ajaxUrls.releaseSubEvent;
        if (!sd.downsSet) {
          mui.toast("请选择下发单位");
          flag = false;
        }
      } else {
        sd.articleID = this.id;
        ajUrl = {
          20: _ajaxUrls.eventRelease,
          30: _ajaxUrls.riskRelease,
          100: _ajaxUrls.riskRelease,
        }[this.urlType];
        //值班员发布
        if (self.details.control.zbyRelease) {
          let needArr = [
            {
              list: [
                {
                  label: "应对要求",
                  isRequired: 1,
                  attributesValue: sd.replyClaim
                },
                {
                  label: "发布单位",
                  isRequired: 1,
                  attributesValue: sd.downsSet
                },
              ]
            }
          ];
          flag = _methods.checkRequired(needArr);
        }
        if (self.details.control.dwPush) {
          let needArr = [
            {
              list: [
                {
                  label: "下发单位",
                  isRequired: 1,
                  attributesValue: sd.downsSet
                },
                {
                  label: "应对要求",
                  isRequired: 1,
                  attributesValue: sd.replyClaim
                },
              ]
            }
          ];
          flag = _methods.checkRequired(needArr);
        }
      }

      if (flag) {
        _ajax.confirmWithLoading(ajUrl.url, sd,
          () => {
            _alert.alert(() => {
              if (self.flag === 2) {
                self.detailRefreshMyTask(2);
              } else {
                self.detailRefresh(1);
              }
            }, '发布成功');
          },
          ajUrl.type, '是否确认发布?');
      }

    },
    goOrgList(code) {
      _methods.goPath(this.dPath + 'orgList?code=' + code);
    },
    myTaskSubmit() {
      let self = this;
      let flag = _methods.checkRequired([{list: this.details.attributeList}]);
      if (flag) {
        let attributeBeanJSON = _methods.temSubmit(this.details.attributeList);
        let data = {
          id: this.id,
          status: 1,
          response: _methods.getValue("response"),
          attributeBeanJSON: JSON.stringify(attributeBeanJSON),
        };
        _ajax.confirmWithLoading(_ajaxUrls.selfTasksSubmit.url,
          data,
          () => {
            self.detailRefresh();
            _alert.alert(() => {
            });
          },
          _ajaxUrls.selfTasksSubmit.type);
      }
    },
    _deleteFeedBackItemCheck(index, key) {
      this.$store.state[key].splice(index, 1);
    },
    goFeedBackItem(type, flag = 1) {
      _methods.goPath(`${this.dPath}feedBackItem?isFeedback=${type}&id=${this.details.templateID}&flag=${flag}`);
    },
    goFeedBackHistory(item, type) {
      // type :1：响应反馈    2：协调处置
      _data.feedBackHistoryID = item.id;
      _data.feedBackHistoryType = type;
      _methods.goPath(`${this.dPath}feedBackHistory`);
    },
    checkFeedBackHistory() {
      // type :1：响应反馈    2：协调处置
      let type = _data.userInfo.roleRank == 5 ? 2 : 1;
      this.goFeedBackHistory({id: this.id}, type);
    },
    //处理反馈
    dealFeedBack(item, type = 1, isDownsSet = 1) {
      console.log();
      _data.feedBackChecked = item;
      _data.reDetail = this.details;
      _methods.goPath(`${this.dPath}feedBackContinue?type=${type}&flag=${this.flag}&isDownsSet=${isDownsSet}`);
    },
    //终止反馈
    feedBackEnd(item, type) {
      let data = {
        fId: item.id,
        content: "终止反馈",
        exStatus: 3,
        infoType: 3
      };
      _ajax.confirmWithLoading(_ajaxUrls.feedBackContinue.url,
        data,
        () => {
          this.init();
          if (this.flag == 1) {
            window._methods.indexLIstRefresh();
          }
          if (this.flag == 2) {
            window._methods.myTaskLIstRefresh();
          }
        }, _ajaxUrls.feedBackContinue.type);
    },
  },
  mounted() {
    let self = this;
    window._vrvInit.isPush().then(() => {
      this.init();
    });
    _data.bus.$on('toLeader', () => {
      setTimeout(() => {
        self.eventSubmit(1);
      }, 100);
    });
    _data.bus.$on('refresh', () => {
      setTimeout(() => {
        self.init();
      }, 100);
    });
    _data.bus.$on('tool', (v) => {
      self.actionCheck = {
        index: 0,
        item: v.item,
      };
      if (v.action) {
        self.toolEditShow(v.item, 0, 1);
        return false;
      }
      self.actionClick(v.value);
    });
  },
  beforeDestroy() {
    _methods.headerTitleChange(this.headerType, true);
    _data.bus.$off("toLeader");
    _data.bus.$off("refresh");
    _data.bus.$off("tool");
    _data.bus.$off("emAdd");
  },
  components: {
    foldWrap,
    actionSheet,
    textarea_y,
    voiceTxtArea,
    detailTemplate,
    leaderAdviseList,
    templateItems,
    phoneCall,
    zjJudgeList,
  },
}
